package com.yand.redis;


import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.Response;

import java.io.IOException;

/**
 * redis 简单限流
 */

public class SimpleRateLimter {

    private Jedis jedis;

    public SimpleRateLimter(Jedis jedis){
        this.jedis = jedis;
    }


    /**
     * 例如 ： 60秒内限制调用5次
     *
     *
     * 简单限流的代码实现
     * @param userId 用户标识
     * @param actionKey 键
     * @param period
     * @param maxCount
     * @return
     */
    public boolean isActionAllowed(String userId, String actionKey, int period, int maxCount) throws IOException {
       String key = userId+actionKey;
       long nowTs = System.currentTimeMillis();
       Pipeline pipe = jedis.pipelined();
       pipe.multi();
       pipe.zadd(key,nowTs,""+nowTs);
       pipe.zremrangeByScore(key,0,nowTs-period*1000);
       Response<Long> count = pipe.zcard(key);

       //pipe.expire(key,period + 1);

       pipe.exec();

       pipe.close();

       return count.get() <= maxCount;

    }



    public static void main(String [] args){
        Jedis jedis =  RedisUtil.getJedis();
        SimpleRateLimter simpleRateLimter = new SimpleRateLimter(jedis);
        for(int i  =0 ; i < 20; i ++){
            try {
                System.out.println(simpleRateLimter.isActionAllowed("yand","reply", 60,5));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
